import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CopilotConfig as CopilotConfigEntity } from '../../database/entities/copilot-config.entity';

export enum ProxyMode {
  MOCK = 'mock',
  COPILOT = 'copilot'
}

export interface ProxyServerConfig {
  enabled: boolean;
  url: string;
  username?: string;
  password?: string;
}

export interface CopilotConfig {
  apiUrl: string;
  githubToken: string;
  authToken: string;
  defaultModel: string;
  timeout: number;
  retryAttempts: number;
  userAgent: string;
  headers: Record<string, string>;
  proxy?: ProxyServerConfig;
}

@Injectable()
export class ProxyConfigService {
  private currentMode: ProxyMode = ProxyMode.MOCK;
  
  constructor(
    @InjectRepository(CopilotConfigEntity)
    private readonly copilotConfigRepository: Repository<CopilotConfigEntity>
  ) {}

  getProxyMode(): ProxyMode {
    return this.currentMode;
  }
  
  setProxyMode(mode: ProxyMode): void {
    this.currentMode = mode;
  }

  async getCopilotConfig(): Promise<CopilotConfig> {
    const dbConfig = await this.getDatabaseConfig();
    
    return {
      apiUrl: dbConfig.apiUrl || 'https://api.business.githubcopilot.com',
      githubToken: dbConfig.githubToken || '',
      authToken: dbConfig.authToken || '',
      defaultModel: dbConfig.defaultModel || 'claude-3.5-sonnet',
      timeout: dbConfig.timeout || 30000,
      retryAttempts: dbConfig.retryAttempts || 3,
      userAgent: dbConfig.userAgent || 'GithubCopilot/1.348.0',
      headers: {
        'content-type': 'application/json',
        'copilot-integration-id': 'jetbrains-chat',
        'copilot-language-server-version': '1.348.0',
        'editor-plugin-version': 'copilot-intellij/1.5.52-243',
        'editor-version': 'JetBrains-IU/243.26574.91',
        'openai-intent': 'conversation-panel',
        'openai-organization': 'github-copilot',
        'x-github-api-version': '2025-05-01',
        'x-initiator': 'user',
        'x-interaction-type': 'conversation-panel',
        'vscode-machineid': '19b5defbe3cc1f1e613f1a91d3049e31b357409dd24187fad57a9c2b9c80f0a2',
        'vscode-sessionid': '114b2e81-1bc7-46f1-a0e8-7a0fe9f83db31754313576054'
      },
      proxy: await this.getProxyConfig()
    };
  }

  async isDebugMode(): Promise<boolean> {
    const dbConfig = await this.getDatabaseConfig();
    return dbConfig.debugMode || false;
  }

  async getRequestTimeout(): Promise<number> {
    const dbConfig = await this.getDatabaseConfig();
    return dbConfig.timeout || 30000;
  }

  async getMaxRetries(): Promise<number> {
    const dbConfig = await this.getDatabaseConfig();
    return dbConfig.retryAttempts || 3;
  }

  async shouldLogRequests(): Promise<boolean> {
    const dbConfig = await this.getDatabaseConfig();
    return dbConfig.logRequests || false;
  }

  async shouldLogResponses(): Promise<boolean> {
    const dbConfig = await this.getDatabaseConfig();
    return dbConfig.logResponses || false;
  }

  async getProxyConfig(): Promise<ProxyServerConfig> {
    const dbConfig = await this.getDatabaseConfig();
    return {
      enabled: dbConfig.proxyEnabled || false,
      url: dbConfig.proxyUrl || '',
      username: dbConfig.proxyUsername || '',
      password: dbConfig.proxyPassword || ''
    };
  }
  
  private async getDatabaseConfig(): Promise<CopilotConfigEntity> {
    let config = await this.copilotConfigRepository.findOne({
      where: { configName: 'default', isActive: true }
    });
    
    if (!config) {
      config = this.copilotConfigRepository.create({
        configName: 'default',
        isActive: true
      });
      config = await this.copilotConfigRepository.save(config);
    }
    
    return config;
  }
}